#include "sc03.h"

#include "iot_uart.h"

#include <string.h>

/* 串口号 */
#define SC03_UART_ID EUART0_M0
/* sc03 数据长度 */
#define SC03_DATA_LENGTH 9

/**
 * @brief sc03 初始化
 *
 */
void sc03_init(void)
{
    IotUartAttribute attr;

    attr.baudRate = 9600;
    attr.dataBits = IOT_UART_DATA_BIT_8;
    attr.pad = IOT_FLOW_CTRL_NONE;
    attr.parity = IOT_UART_PARITY_NONE;
    attr.rxBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK;
    attr.stopBits = IOT_UART_STOP_BIT_1;
    attr.txBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK;

    IoTUartInit(SC03_UART_ID, &attr);
}

/**
 * @brief 获取 sc03 数据
 *
 * @return double
 */
double sc03_get(void)
{
    int8_t ret = 0;
    uint8_t buf[SC03_DATA_LENGTH] = {0};
    uint8_t packet_hand[] = {0xFF, 0x86, 0x00};
    static double last_data = 0.0;

    ret = IoTUartRead(SC03_UART_ID, buf, SC03_DATA_LENGTH);
    if (ret < 0)
    {
        printf("read uart fail, ret is %d\r\n", ret);
        return;
    }

    uint8_t *ptr = strstr(buf, packet_hand);

    if ((ptr[0] != packet_hand[0]) && (ptr[1] != packet_hand[1]))
    {
        return last_data;
    }

    double ppm = (ptr[2] * 256 + ptr[3]) * 0.1;
    last_data = ppm;

    return ppm;
}
